package com.hxzon.aixzsecretary.net;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import com.hxzon.aixzsecretary.util.AixzObservable;
import com.hxzon.aixzsecretary.util.AixzSensor;

public class UdpServer extends Thread implements AixzObservable {

	private AixzSensor sensor;

	public UdpServer() {
		sensor = new AixzSensor(this);
	}

	public AixzSensor getSensor() {
		return sensor;
	}

	public void run() {
		DatagramSocket dSocket;
		DatagramPacket inPacket;
		DatagramPacket outPacket;
		InetAddress cAddr;
		int cPort;
		byte[] inBuffer = new byte[100];
		byte[] outBuffer;
		String ins;
		String outs;
		String k;
		IPuserData ipUserData = new IPuserData();

		try {
			dSocket = new DatagramSocket(3001);
			while (true) {
				inPacket = new DatagramPacket(inBuffer, inBuffer.length);
				dSocket.receive(inPacket);
				System.out.println("receive udpClient");
				cAddr = inPacket.getAddress();// 客户端的IP
				cPort = inPacket.getPort();

				k = new String(inPacket.getData(), 0, 3);
				ipUserData.state = k;
				ins = new String(inPacket.getData(), 3,
						inPacket.getLength() - 3);
				ipUserData.user = ins;
				String s2 = (inPacket.getAddress()).toString();
				ipUserData.ip = s2;
				sensor.setData(ipUserData);// 改变Observable
				sensor.notifyObservers();// 通知observer，对象已改变

				if (!(ipUserData.state.equals("del"))) {
					outs = "";
					outs = System.getProperty("user.name");
					outs = "add" + outs;
					outBuffer = outs.getBytes();
					outPacket = new DatagramPacket(outBuffer, 0,
							outBuffer.length, cAddr, cPort);
					dSocket.send(outPacket);
				} else {
					outs = "";
					outs = System.getProperty("user.name");
					outs = "del" + outs;
					outBuffer = outs.getBytes();
					outPacket = new DatagramPacket(outBuffer, 0,
							outBuffer.length, cAddr, cPort);
					dSocket.send(outPacket);
				}
			}
		} catch (IOException e) {
			System.out.println("udpserver run exception");
		}

	}
}
